﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using TSites.Config;
using TSites.Xml;

namespace TSites.Language
{
    public class TsLanguage
    {
        private static TsLanguage _instance;
        private static TsXmlEngine _xmlEngine;
        private static Dictionary<string, Object> _laguage;

        /// <summary>
        /// Multilanguage resource
        /// </summary>
        private TsLanguage() { }// Constructor

        public static TsLanguage GetInstance()
        {
            if (_instance == null)
            {
                _instance = new TsLanguage();
                _instance.Load();
            }            
            return _instance;
        }

        private void Load()
        {
            _laguage = new Dictionary<string, Object>();
            TsConfig config = TsConfig.GetInstance();
            string languagePath = config.LanguagePath;
            string[] filePaths = Directory.GetFiles(languagePath, "*.txt");
            FileInfo file;
            if (filePaths != null)
            {
                for (int i = 0; i < filePaths.Length; i++)
                {
                    _xmlEngine = new TsXmlEngine(filePaths[i]);
                    file = new FileInfo(filePaths[i]);
                    _laguage.Add(file.Name.Substring(0, file.Name.Length - file.Extension.Length), _xmlEngine);//.txt = 4
                }
            }           
        }

        public String GetValue(String keyValue, string languageType=null)
        {
            string value = "";
            TsConfig config = TsConfig.GetInstance();
            if (languageType == null || languageType == "")
                languageType = config.DefaultLanguage;
            if (languageType != null)
            {
                if (_laguage.ContainsKey(languageType))
                {
                    TsXmlEngine reader = (TsXmlEngine)_laguage[languageType];
                    if (reader != null)
                        value = reader.GetContent("msgId", keyValue);
                }                
            }
            return value;
        }
    }
}